package com.cci.kangdao.service.impl;

import com.alibaba.fastjson.JSON;
import com.cci.kangdao.aop.UserThreadLocal;
import com.cci.kangdao.dao.*;
import com.cci.kangdao.dao.model.*;
import com.cci.kangdao.externalData.dto.request.LyhFileUserRequest;
import com.cci.kangdao.externalData.service.ExternalDataSynchroService;
import com.cci.kangdao.model.ConductionInfo;
import com.cci.kangdao.redis.RedisClientUtils;
import com.cci.kangdao.service.AsyncCrmService;
import com.cci.kangdao.service.UserService;
import com.cci.kangdao.utilTool.*;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author William Du
 * @date 2019/10/14
 */
@Service
public class UserServiceImpl implements UserService {

    private Logger log = Logger.getLogger(this.getClass().getName());


    @Resource
    private UserTDao userTDao;
    @Resource
    private LoginDao loginDao;
    @Resource
    private RolesTDao rolesTDao;
    @Resource
    private RolesHandleTDao rolesHandleTDao;
    @Resource
    private RoleChannelTDao roleChannelTDao;
    @Resource
    private RedisClientUtils redisClientUtils;
    @Resource
    private SSRepairTDao ssRepairTDao;
    @Resource
    private MemberDao memberDao;
    @Resource
    private CompanyTDao companyTDao;
    @Resource
    private ServiceStationOemRelationTDao serviceStationOemRelationTDao;
    @Resource
    private AsyncCrmService asyncCrmService;
    @Resource
    private ServiceAgrementDao saDao;
    @Resource
    private UserLabelMapper userLabelMapper;
    @Resource
    private DictionariesTDao dictionariesTDao;
    @Resource
    private ServiceAgrementDao serviceAgrementDao;
    @Resource
    private ExternalDataSynchroService externalDataSynchroService;
    @Resource
    private UserChannelTMapper userChannelTMapper;

    //新角色添加服务工单功能项时，需要把function表中url配置到这
    private static final List<String> SS_FUNCTIONS = Arrays.asList(new String[]{"22", "23", "24", "25", "30", "34", "40", "45", "49", "53", "60", "64", "69", "73", "81", "86", "106"});
    private static final List<String> DR_FUNCTIONS = Arrays.asList(new String[]{"38"});

    private Pattern WWID_PATTERN = Pattern.compile("^([A-Za-z]{2})([0-9A-Za-z]{3})$");

    /**
     * App获取个人信息接口
     *
     * @param map
     * @return
     */
    @Override
    public void getUserInfo(Map map) {
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        try {
            UserT userT = UserThreadLocal.get();
            JSONObject obj = new JSONObject();
            obj.put("status", 0);
            obj.put("msg", "");
            obj.put("username", userT.getUserName());
            //用户头像
            UserT userT1 = userTDao.selectById(userT.getId());
            if(null != userT1){
                obj.put("adUserId", userT1.getAduserId());
                obj.put("isInitWaInfo", null != userT1.getIsInitWaInfo() ? userT1.getIsInitWaInfo() : 0);
                obj.put("inviteCode", userT1.getInviteCode());
                obj.put("referralCode", userT1.getReferralCode());
                obj.put("photoUrl", userT1.getPhotoUrl());
                obj.put("contact", StringUtils.isEmpty(userT1.getContact())?"":AESTool.encryptString(userT1.getContact()));
                int i = userTDao.isEndUser(userT.getId());
                Integer guideType = userT1.getGuideType();
                if(i <= 0){
                    guideType = 0;
                }

                obj.put("guideType", guideType);
                Integer guideFunType = userT1.getGuideFunType();
                if(i <= 0){
                    guideFunType = 0;
                }
                obj.put("guideFunType", guideFunType);
                String businessNo = userTDao.getBusinessByUserId(userT.getId());
                obj.put("businessNo", businessNo);
                String serviceChannel = "1";
                List<UserChannelT> channelList = userChannelTMapper.getUserChannelListByUserId(userT.getId());
                if(CollectionUtils.isNotEmpty(channelList)){
                    serviceChannel = channelList.get(0).getServiceChannel();
                }
                obj.put("serviceChannel", serviceChannel);
            }

            ConductionInfo conductionInfo = userTDao.getConductionByUserId(userT.getId());
            obj.put("conductionInviteCode", null != conductionInfo ? conductionInfo.getInvitationCode() : "");

            int isType = userT.getIsType();
//            int gmAuthStatus = 0;

            if (isType == 6) {//isType; 1是康明斯，2，康明斯分公司，3是JV，4是OEM，5是SSOEM，6是Dealer，0是Engine Customer
//                if (loginDao.getGMAuthStatusByServiceStationId(userT.getServiceStationID()) > 0) {
//                gmAuthStatus = 1;
//                }
                //判断服务站是否被大运授权
                int serviceStationOemRelationCountByStationId = serviceStationOemRelationTDao.getServiceStationOemRelationCountByStationId(userT.getServiceStationID());
                if (serviceStationOemRelationCountByStationId > 0) {
                    obj.put("isDyServiceStation", 1);
                } else {
                    obj.put("isDyServiceStation", 0);
                }
                //3.2.0  如果是服务站用户   多返回授权渠道集合
                String companyNos = ssRepairTDao.getCompanyNoByServiceStationId(userT.getServiceStationID());
                obj.put("companyNos", companyNos);
            }
            if (isType == 3 || isType == 1) {
//                if (loginDao.getGMAuthStatusByCompanyId(userT.getCompanyId()) > 0) {
//                gmAuthStatus = 1;
//                }
            }

            obj.put("istype", isType);
            obj.put("mobile", AESTool.encryptString(userT.getPhone()));
            obj.put("promotionId", StringUtils.isEmpty(userT.getPromotionId()) ? "" : userT.getPromotionId());

            //返给手机端角色
            map.put("UserID", String.valueOf(userT.getId()));
            List<RolesT> rolesTList = rolesTDao.getRoleListByUserID(userT.getId());
//            for (RolesT rolesT : rolesTList) {
//                if (Objects.equals(rolesT.getIsGuidanz(),1)){
//                    gmAuthStatus = 1;
//                }
//            }
            //关闭guidanz 功能
            obj.put("GMAuthStatus", 0);
            Integer isHandler = 0;
            JSONArray rolesTListJA = new JSONArray();
            Boolean isTechnician = Boolean.FALSE;
            for (RolesT rolesT : rolesTList) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("Id", rolesT.getId());
                jsonObject.put("RolesNo", rolesT.getRolesNo());
                jsonObject.put("RolesName", rolesT.getRolesName());
                jsonObject.put("CompanyId", rolesT.getCompanyId());
                jsonObject.put("Describes", rolesT.getDescribes());
                jsonObject.put("Systime", rolesT.getSystime());
                rolesTListJA.put(jsonObject);
                if (rolesT.getIsHandler().equals(1)) {
                    isHandler = 1;
                }
                // 用户是服务技师，判断其服务商是否被是否DBU
                if (rolesT.getRolesNo().equals("R0033")) {
                    isTechnician = Boolean.TRUE;
                }
            }
            obj.put("rolesTList", rolesTListJA);
            //1是康明斯，2，康明斯分公司，3是JV，4是OEM，5是SSOEM，6是Dealer，0是Engine Customer
            if (userT.getIsType() == 0) {
                obj.put("companyName", "");
                obj.put("deptName", "");
            } else {
                UserT userCompany = loginDao.getUserCompanyDept(userT.getId());
                if (userCompany.getCompanyName() == null) {
                    obj.put("companyName", "");
                } else {
                    obj.put("companyName", userCompany.getCompanyName());
                }
                obj.put("deptName", "");
            }
            /**
             * 查询服务站信息
             */
            List<FunctionT> functionList = loginDao.getAllFunctionByUserid(userT.getId());
            obj.put("companyId", String.valueOf(userT.getCompanyId()));
            //初始化登录人是否具有服务流程权限   默认值为0   否
            int ssFunStatus = 0;
            //初始化登录人是否具有诊断维修权限   默认值为0   否
            int drFunStatus = 0;
            ServiceStationT serviceStationT = null;
            // 资质是否显示开关
            int promotionShow = 0;
            if (userT.getServiceStationID() != 0) {
                serviceStationT = loginDao.getServiceStationById(userT.getServiceStationID());
                List<ServiceStationT> serviceStationT1 = loginDao.getBusinessNo(userT.getServiceStationID());
                if (serviceStationT1.size() > 0) {
                    Map<Object, Object> lm = new HashMap<>();
                    for (ServiceStationT stationT : serviceStationT1) {
                        lm.put(stationT.getCompanyID(), stationT.getBusinessNo());
                    }
                    obj.put("stationCrmNos", lm);
                } else {
                    Map<Object, Object> m1 = new HashMap<>();
                    obj.put("stationCrmNos", m1);
                }

                obj.put("serviceStationID", AESTool.encryptString("" + userT.getServiceStationID()));

                obj.put("stationName", serviceStationT != null ? serviceStationT.getStationname() : "");
                obj.put("stationRelationType", (serviceStationT != null && serviceStationT.getRelationType() != null) ? serviceStationT.getRelationType() : 1);
                if (hasFunction(functionList, SS_FUNCTIONS)) {
                    ssFunStatus = serviceStationT.getSsfunstatus();
                }
                if (hasFunction(functionList, DR_FUNCTIONS)) {
                    drFunStatus = serviceStationT.getDrfunstatus();
                }
                // 当前用户是服务商技师，判断其是否被CCI授权
                if (isTechnician) {
                    List<Map<String, Object>> ssRepairTS = ssRepairTDao.getSSRepairTByServiceStationID(serviceStationT.getId());
                    if (CollectionUtils.isNotEmpty(ssRepairTS)) {
                        for (Map<String, Object> ssRepairMap : ssRepairTS) {
                            Long companyId = MapUtils.getLong(ssRepairMap, "CompanyID");
                            if (companyId.equals(1L)) {
                                promotionShow = 1;
                            }
                        }
                    }
                }
                obj.put("serviceStationCategory", serviceStationT.getServiceStationCategory());
            } else {
                obj.put("serviceStationID", AESTool.encryptString("" + userT.getServiceStationID()));
                obj.put("stationName", "");
                if (hasFunction(functionList, SS_FUNCTIONS)) {
                    ssFunStatus = 1;
                }
                if (hasFunction(functionList, DR_FUNCTIONS)) {
                    drFunStatus = 1;
                }
            }
            //根据服务商信息返回对应授权渠道信息
            List<String> companyNosList = companyTDao.getServiceChannelByStationId(userT.getServiceStationID()).stream()
                    .map(companyT -> companyT.get("CompanyNo").toString()).distinct().collect(Collectors.toList());
            obj.put("serviceStationChannel", String.join(",", companyNosList));
            obj.put("promotionShow", promotionShow);
            obj.put("wwID", userT.getEmployeeNum());
            obj.put("position", userT.getPosition());
            obj.put("integral", AESTool.encryptString("" + userT.getIntegral()));
            obj.put("AESId", getUserSort(userT.getId()));
            obj.put("dealerLevel", userT.getDealerLevel());
            obj.put("usergroupName", userT.getUsergroupName());
            obj.put("usergroupSubName", userT.getUsergroupSubName() == null ? "" : userT.getUsergroupSubName());
            obj.put("remark", userT.getRemark());
            obj.put("type", userT.getType());
            obj.put("email", userT.getEmail());
            //拼装权限申请和查看参数
            obj.put("isApplicant", 1);
            if (isHandler.equals(0)) {
                List<RolesHandleT> handleTList = rolesHandleTDao.selectHandleListByHandlerId(userT.getId());
                if (CollectionUtils.isNotEmpty(handleTList)) {
                    isHandler = 1;
                }
            }
            obj.put("isHandler", isHandler);
            obj.put("SSFunStatus", ssFunStatus);
            obj.put("DRFunStatus", drFunStatus);
            // 拼装角色渠道
            Integer roleChannel = 0;
            if (NumberUtils.isPositiveNum(userT.getCompanyId())) {
                // 企业用户
                Map<String, Object> roleChannelData = roleChannelTDao.getRoleChannelByCompanyId(userT.getCompanyId());
                if (MapUtils.isNotEmpty(roleChannelData)) {
                    roleChannel = 1;
                }
            } else if (NumberUtils.isPositiveNum(userT.getServiceStationID())) {
                // 服务商用户
                Integer serviceStationCategory = serviceStationT.getServiceStationCategory();
                // 非空非零数据
                if (NumberUtils.isPositiveNum(serviceStationCategory)) {
                    if (serviceStationCategory.equals(1)) {
                        // 普通服务商用户
                        roleChannel = 2;
                    } else {
                        // CHS，分公司,区域BU类型服务商归类为分公司用户
                        roleChannel = 3;
                    }
                } else {
                    // 数据问题，将用户归类为普通服务商用户
                    roleChannel = 2;
                }
            } else {
                // 普通用户
                roleChannel = 0;
            }
            obj.put("roleChannel", roleChannel);
            //增加是否是大运会员标志
            int isDYMember = memberDao.getIsDYMemberByUserId(userT.getId());
            obj.put("isDYMember", isDYMember);
            //返回客户
            //查询用户所属的biaoqian
            List<Integer> userLabels = userLabelMapper.getUserLabel(userT.getId());
            String userLabel = StringUtils.join(userLabels, ",");
            obj.put("userLabel", userLabel);
            //更新  ip 和地址信息
            if (StringUtils.isBlank(userT1.getIp()) && StringUtils.isBlank(userT1.getProvince()) && StringUtils.isBlank(userT1.getCity())) {
                HttpServletRequest request = (HttpServletRequest) map.get("request");
                String ip = RequestIPUtils.getRequestClientRealIp(request);
                //通过ip获取省市
                userT1 = GDRegion.addProviceAndCity(ip, userT1);
                userTDao.updateCityAndproviceSelective(userT1);
            }
            //增加是否会员标志
            int isVip = memberDao.getIsVipByUserId(userT.getId(), LocalTimeUtil.getFormatterRealCurrentTime(LocalTimeUtil.DTF_DATE_FORMATTER));
            obj.put("isVip", isVip > 0 ? 1 : 0);
            //是否支持购买会员 0不支持|1支持
            String supportPay = dictionariesTDao.getListByDTableNameAndDInt("vipSupportPay","0");
            obj.put("supportPay", StringUtils.isNotBlank(supportPay) ? Integer.valueOf(supportPay) : 0);
            //获取是否添加芯管家主动服务协议
            obj.put("coreButler", false);
            obj.put("coreButlerVersion", 0);
            //是否首次登录
            obj.put("isShowCompleteInfo", userT1.getIsShowCompleteInfo());


            //获取主动升级的按钮字典项
            String coreManagerAgreementFlag = dictionariesTDao.getListByDTableName("CoreManagerAgreementFlag");
            if (StringUtils.isNotBlank(coreManagerAgreementFlag) && Boolean.valueOf(coreManagerAgreementFlag)) {
                String coreManagerAgreement = dictionariesTDao.getListByDTableName("CoreManagerAgreement");
                //查询 协议的版本符号
                ServiceAgreement serviceAggrementDetailAndVersion = serviceAgrementDao.getServiceAggrementDetailAndVersion(userT.getId(), LocalTimeUtil.getRealCurrentTime(), 3, Integer.valueOf(coreManagerAgreement));
                obj.put("coreButler", null != serviceAggrementDetailAndVersion);
                obj.put("coreButlerVersion", null == serviceAggrementDetailAndVersion ? 0 : serviceAggrementDetailAndVersion.getVersion());
            }else{//如果协议关闭直接 可以弹框
                obj.put("coreButler", true);
            }
            ParameterTool.writeResponse(response, obj.toString());
            obj = null;
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            ParameterTool.writeErrorResponse(response);
        }
    }

    /**
     * 更新用户指引类型
     * @param map 请求MAP
     */
    @Override
    public void updateGuideType(Map map) {
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        //默认是首页指引 0 , 全部功能指引 1
        int type = MapUtils.getInteger(map, "type", 0);
        // 获取当前用户
        UserT userT = UserThreadLocal.get();
        if(type == 0){
            userTDao.updateGuideTypeByUserId(userT.getId());
        } else if(type == 1){
            userTDao.updateGuideFunTypeByUserId(userT.getId());
        }

        ParameterTool.writeSuccessResponse(response);
    }

    @Override
    @Transactional
    public void updateUserInfo(Map map) {
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        try {
            String contact = AESTool.decryptString(MapUtils.getString(map, "contact", ""));
            String phone = AESTool.decryptString(MapUtils.getString(map, "mobile", ""));

            String servicePhone = MapUtils.getString(map, "servicePhone", "");
            String remark = MapUtils.getString(map, "remark", "");
            // 判断必填字段
            if (StringUtils.isEmpty(contact) || StringUtils.isEmpty(phone)) {
                ParameterTool.writeErrorResponse(response, -5);
            }
            // 获取当前用户
            UserT userT = UserThreadLocal.get();
            // 判断手机号是否被其他账号使用
            List<UserT> userTList = loginDao.getUserByPhone(phone);
            if (CollectionUtils.isNotEmpty(userTList)) {
                for (UserT existUser : userTList) {
                    // 手机号用户不是当前用户
                    if (existUser.getId() != userT.getId()) {
                        ParameterTool.writeResponse(response, 1, "手机号已被其他账户使用，请检查确认!");
                        return;
                    }
                }
            }
            // 判断手机号是否是其他账户的用户名
            UserT userNameUser = loginDao.getUserByUserName(phone);
            if (null != userNameUser && userNameUser.getId() != userT.getId()) {
                ParameterTool.writeResponse(response, 1, "手机号已被其他账户使用，请检查确认！");
                return;
            }
            // 更新用户信息
            userT.setContact(contact);
            userT.setPhone(phone);

            userT.setServicePhone(servicePhone);

            userT.setRemark(remark);
            userT.setPhotoUrl(MapUtils.getString(map, "photoUrl", ""));
            int flag = loginDao.updateUser(userT);
            //更新用户的标签
            String userLabels = MapUtils.getString(map, "userLabel");
            Integer downloadChannel = MapUtils.getInteger(map, "downloadChannel");
            if (StringUtils.isNotBlank(userLabels)) {
                userLabelMapper.deleteByPrimaryKey(userT.getId());
                List<String> userLabelList =Arrays.asList(userLabels.split(","));
                for(String userLabel : userLabelList){
                    UserLabel label = new UserLabel();
                    label.setLaberType(Integer.valueOf(userLabel));
                    label.setDownloadChannel(downloadChannel);
                    label.setUserId(userT.getId());
                    label.setFlag(0);
                    label.setCreator(userT.getId());
                    label.setCreateTime(LocalTimeUtil.getRealCurrentTime());
                    label.setIsRead(1);
                    userLabelMapper.insert(label);
                }
            }

            //
            userT = loginDao.getUserByid(String.valueOf(userT.getId()));
            Long count =  saDao.isSignAgreement(userT.getId(), LocalTimeUtil.getRealCurrentTime());

            // 判断更新情况
            if (flag > 0) {
                //同步老友会用户
                LyhFileUserRequest userRequest = new LyhFileUserRequest();
                userRequest.setUserId(userT.getId());
                userRequest.setContact(contact);
                externalDataSynchroService.pushLyhUser(userRequest);
                if(count>0){//用户如果签署了主动服务协议，将发动机信息同步至salesforce
                    asyncCrmService.syncUserInfoToCRM(userT, true);
                }else{
                    asyncCrmService.syncUserInfoToCRM(userT, false);
                }
                //更新成功后删除缓存
                redisClientUtils.delkey("userT" + userT.getId());
                ParameterTool.writeSuccessResponse(response);
            } else {
                ParameterTool.writeErrorResponse(response);
            }
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            ParameterTool.writeErrorResponse(response);
        }
    }

    /**
     * 小蜜蜂打开用户修改标签接口
     * @param userLabels
     * @return
     */
    @Override
    public boolean upholdUserLabel(String userLabels) {
        UserT userT = UserThreadLocal.get();
        int i = 0;
        if (StringUtils.isNotBlank(userLabels)) {
            userLabelMapper.deleteByPrimaryKey(userT.getId());
            List<String> userLabelList =Arrays.asList(userLabels.split(","));
            for(String userLabel : userLabelList){
                UserLabel label = new UserLabel();
                label.setLaberType(Integer.valueOf(userLabel));
                label.setDownloadChannel(4);
                label.setUserId(userT.getId());
                label.setFlag(0);
                label.setCreator(userT.getId());
                label.setCreateTime(LocalTimeUtil.getRealCurrentTime());
                label.setIsRead(1);
                i += userLabelMapper.insert(label);
            }
            UserT user = new UserT();
            user.setId(userT.getId());
            user.setIsInitWaInfo(1);
            userTDao.updateUserMsgById(user);
        }
        return i > 0;
    }

    @Override
    public void checkUserAcce(Map<String, Object> map) {
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        try {
            // 获取当前用户
            UserT userT = UserThreadLocal.get();
            JSONObject obj = new JSONObject();   //保存返给手机端的数据容器
            Map<String, Object> dataMap = new HashMap<>();   //保存data
            dataMap.put("gmAuth", 0);
            // 判断是否为站长
            Long headerStatus = userTDao.checkHeaderStatusById(userT.getId());
            if (null != headerStatus) {
                dataMap.put("gmAuth", 1);
            }
            //判断是否为审批人
            Long approverStatus = userTDao.checkApproverStatusById(userT.getId());
            if (null != approverStatus) {
                dataMap.put("gmAuth", 1);
            }
            obj.put("status", "0");
            obj.put("msg", "success");
            obj.put("data", dataMap);
            ParameterTool.writeResponse(response, obj.toString());
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            ParameterTool.writeErrorResponse(response);
        }
    }

    @Override
    public void getUserByToken(Map<String, Object> map) {
        UserT userT = UserThreadLocal.get();
//        UserTVo userTVo = new UserTVo();
//        BeanUtils.copy(userT, userTVo);
        ParameterTool.writeSuccessResponse(RequestContextHolder.getResponse(), userT);
    }

    @Override
    public void getUserById(Map<String, Object> map) {
        Long userId = MapUtils.getLong(map, "userId", 0L);
        UserT userT = userTDao.selectById(userId);
        ParameterTool.writeSuccessResponse(RequestContextHolder.getResponse(), userT);
    }

    private Boolean hasFunction(List<FunctionT> functionTList, List<String> funUrlList) {
        for (FunctionT functionT : functionTList) {
            if (funUrlList.contains(functionT.getFunUrl())) {
                return true;
            }
        }
        return false;
    }

    private String getUserSort(long userId) {
        char[] xmString = {'1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'A', 'B', 'C', 'D', 'E'};
        String userIdStr = "";
        if (userId > 999999) {
            userIdStr = String.format("%09d", userId);
        } else {
            userIdStr = String.format("%06d", userId);
        }
        StringBuffer userIdShow = new StringBuffer();
        for (int i = 0; i < userIdStr.length(); i++) {
            userIdShow.append(xmString[(int) (Math.random() * 15)] + userIdStr.substring(i, i + 1));
        }
        return userIdShow.toString();
    }


    //移动技师获取用户推送短信相关信息
    @Override
    public ModelAndView getUserInfoByMT(Map<String, Object> map) {
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        HttpServletRequest request = (HttpServletRequest) map.get("request");
        try {
            JSONObject obj = new JSONObject();  //声明返给前端json对象
            if (map.containsKey("serviceStationId")) {   //获取服务站站长信息员用户信息
                long serviceStationId = MapUtils.getLongValue(map, "serviceStationId", -1);
                List<Map<String, Object>> stationMangerList = userTDao.getStationMangerListFromMTServiceStationID(serviceStationId);
                obj.put("stationMangerList", stationMangerList);
            }
            if (map.containsKey("userIds")) {   //获取用户信息
                String userIds = MapUtils.getString(map, "userIds", "");
                List<String> stringList = StringToool.getStringList(userIds, ",");
                List<Map<String, Object>> usersInfoList = userTDao.getUsersInfoListFromMTUserId(stringList);
                obj.put("usersInfoList", usersInfoList);
            }
            if (map.containsKey("roleNos")) {   //和获取角色下所有用户信息
                String roleNos = MapUtils.getString(map, "roleNos", "");
                List<String> stringList = StringToool.getStringList(roleNos, ",");
                List<Map<String, Object>> roleNosUsersInfoList = userTDao.getRoleNosUsersInfoListFromMTUserId(stringList);
                obj.put("roleNosUsersInfoList", roleNosUsersInfoList);
            }
            obj.put("data", obj.toString());
            obj.put("status", 0);
            obj.put("msg", "success");
            ParameterTool.writeResponse(response, obj.toString());
        } catch (Exception e) {
            ParameterTool.writeErrorResponse(response);
            log.error(e.getMessage(), e);
        }
        return null;
    }


    /**
     * Guidanz申请权限时获取用户的基本信息
     */
	@Override
	public void getUserInfoGuidanz(Map<String, Object> map) {
		HttpServletResponse response = (HttpServletResponse)map.get("response");
		UserT user = UserThreadLocal.get();

		Map<String, Object> result = new HashMap<>();
		result.put("userId", user.getId());
		result.put("phone", user.getPhone());
		result.put("contact", user.getContact());
		result.put("email", user.getEmail());
		result.put("employeeNum", user.getEmployeeNum());
		result.put("serviceStationId", user.getServiceStationID());
		result.put("isWWIDUser", 0);

		result.put("company",  Collections.EMPTY_LIST);

		// 当前用户是否为WWID用户
		if(WWID_PATTERN.matcher(user.getUserName()).matches()){
			result.put("isWWIDUser", 1);
		}
		List<String> hasRoles = userTDao.getUserHasRolesByUserID(user.getId());
		result.put("roles", CollectionUtils.isEmpty(hasRoles) ? Collections.EMPTY_LIST : hasRoles);

		// 查询出用户对应的渠道信息
		long companyId = user.getCompanyId();
		if(companyId > 0) {
			// id, companyName, companyNo,
			Map<String, Object> company = userTDao.getCompanyById(companyId);

			if(Objects.isNull(company)) {

				result.put("company", Collections.EMPTY_LIST );
			}else {

				// 重新修改渠道的名称
				String companyNo = MapUtils.getString(company, "companyNo", "");
				if(Objects.equals(companyNo, "BFCEC")) {
					company.put("companyName", "福田渠道");
				}
				result.put("company", Arrays.asList(company));

				// id,stationName, stationNo
				Map<String, Object> station = new HashMap<>(4);
				station.put("id", company.get("id"));
				station.put("stationName", company.get("companyName"));
				station.put("stationNo", company.get("companyNo"));
				station.put("companyType", 1);
				result.put("serviceStation",  station);

			}

		}

		// 如果是服务站用户需要查询出服务站授权的渠道
		/*
		   特别说明：就当前系统而已，一个用户要么属于某个服务站，要么属于某个渠道，要么2者都不属于（比如：终端用户），
		   不会存在一个用户即属于某个渠道也属于某个服务站
		 */

		long serviceStationID = user.getServiceStationID();
		if(serviceStationID > 0) {

			Map<String, Object> serviceStation = userTDao.getServiceStationById(serviceStationID);
			if(!Objects.isNull(serviceStation)) {
				serviceStation.put("companyType", 2);
				result.put("serviceStation",  serviceStation);
			}

			List<Map<String, Object>> authCompany = userTDao.getAuthCompanyByStationId(serviceStationID);
			result.put("company", Objects.isNull(authCompany) ? Collections.EMPTY_LIST : authCompany);
		}


		ParameterTool.writeSuccessResponse(response, result);
	}


    @Override
    public void getUserInfoByPhone(Map<String, Object> map) {
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        String phone = MapUtil.getMapValue(map, "phone");
        net.sf.json.JSONObject obj = new net.sf.json.JSONObject();
        if (StringUtils.isBlank(phone)) {
            obj.put("data", "请输入手机号");
            obj.put("status", -99);
            obj.put("msg", "fail");
            ParameterTool.writeResponse(response, obj.toString());
        }
        UserT userT = userTDao.checkUserByNameOrPhone(phone);
        obj.put("data", userT.toString());
        obj.put("status", 0);
        obj.put("msg", "success");
        ParameterTool.writeResponse(response, obj.toString());
    }

    @Override
    public void getUserLabel(Map<String, Object> map) {
        UserT userT = UserThreadLocal.get();
        UserLabel label = userLabelMapper.getLabel(userT.getId());
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        if (null == label) {
            com.alibaba.fastjson.JSONObject jsonObject = new com.alibaba.fastjson.JSONObject();
            jsonObject.put("isRead", 0);
            ParameterTool.writeResponse(response, jsonObject.toJSONString());
            return;
        } else {
            ParameterTool.writeResponse(response, JSON.toJSONString(label));
            return;
        }
    }

    @Override
    public void updateOrUpdateSerLabel(Map<String, Object> map) {
        UserT userT = UserThreadLocal.get();
        UserLabel label = userLabelMapper.getLabel(userT.getId());
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        Integer userLabel = MapUtils.getInteger(map, "userLabel");
        Integer downloadChannel = MapUtils.getInteger(map, "downloadChannel");
        if (null == label) {
            //添加
            label = new UserLabel();
            label.setDownloadChannel(downloadChannel);
            label.setLaberType(userLabel);
            label.setUserId(userT.getId());
            label.setFlag(0);
            label.setCreator(userT.getId());
            label.setCreateTime(LocalTimeUtil.getRealCurrentTime());
            label.setIsRead(1);
            userLabelMapper.insert(label);
            ParameterTool.writeResponse(response, JSON.toJSONString(label));
            return;
        } else {
            label.setDownloadChannel(downloadChannel);
            label.setLaberType(userLabel);
            label.setUserId(userT.getId());
            label.setIsRead(1);
            label.setUpdateTime(LocalTimeUtil.getRealCurrentTime());
            label.setUpdator(userT.getId());
            userLabelMapper.updateByPrimaryKeySelective(label);
            ParameterTool.writeResponse(response, JSON.toJSONString(label));
            return;
        }
    }
    @Transactional
    @Override
    public void updateIsShowComplete(Map<String, Object> map) {
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        UserT userT = UserThreadLocal.get();
        UserT userTupdate = new UserT();
        userTupdate.setIsShowCompleteInfo(0);
        userTupdate.setId(userT.getId());
        userTDao.updateUserMsgById(userTupdate);
        ParameterTool.writeSuccessResponse(response);
    }
}
